//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class PasswordRecord : WorksheetLevelRecord
    {
        private ushort _wPassword;

        public PasswordRecord(string passwordHash)
        {
            this._wPassword = GetIntPasswordFromString(passwordHash);
        }

        public PasswordRecord()
        {
        }

        private static ushort GetIntPasswordFromString(string passwordHash)
        {
            Contract.Ensures(GetStringPasswordFromInt(Contract.Result<ushort>()) == passwordHash);
            return ushort.Parse(passwordHash, NumberStyles.HexNumber);
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            _wPassword = context.ReadUInt16();
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.Password; }
        }

        internal override void Apply(BiffReaderWorksheetContext context)
        {
            context.Worksheet.EnsureProtection().PasswordHash = GetStringPasswordFromInt(_wPassword);
        }

        private static string GetStringPasswordFromInt(ushort wPassword1)
        {
            return wPassword1.ToString("X");
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            context.Write(_wPassword);
        }
    }
}